package logic

import (
	"context"
	"strconv"
	"time"

	"go-zero-admin/apps/user/rpc/internal/svc"
	"go-zero-admin/apps/user/rpc/user"
	"go-zero-admin/model"
	"go-zero-admin/pkg/config"
	"go-zero-admin/pkg/errorx"
	"go-zero-admin/pkg/utils"

	"github.com/golang-jwt/jwt/v4"
	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

//  登录
func (l *LoginLogic) Login(in *user.LoginReq) (*user.LoginResp, error) {
	sysUser, err := l.svcCtx.SysUserModel.FindOneByAccount(l.ctx, in.Account)
	if err != nil {
		return nil, errorx.NewDefaultError(errorx.AccountErrorCode)
	}
	if sysUser.Password != utils.MD5(in.Password+l.svcCtx.Config.Salt) {
		return nil, errorx.NewDefaultError(errorx.PasswordErrorCode)
	}
	if sysUser.Status == config.SysDisable {
		return nil, errorx.NewDefaultError(errorx.AccountDisableErrorCode)
	}
	if sysUser.Id != config.SysSuperUserId {
		dept, _ := l.svcCtx.SysUserModel.FindOne(l.ctx, sysUser.DeptId)
		if dept.Status == config.SysDisable {
			return nil, errorx.NewDefaultError(errorx.AccountDisableErrorCode)
		}
	}
	token, _ := l.getJwtToken(sysUser.Id)
	// 暂时放在安排api比较合理 因为生成的时候在api  相关操作包括删除应该在同一服务
	//_, err = l.svcCtx.Redis.Del(in.CaptchaId)

	LoginLog := model.SysLog{
		UserId: sysUser.Id,
		Ip:     in.HeaderGet,
		Uri:    in.RequestURI,
		Type:   1,
		Status: 1,
	}
	_, err = l.svcCtx.SysLogModel.Insert(l.ctx, &LoginLog)
	err = l.svcCtx.Redis.Setex(config.SysOnlineUserCachePrefix+strconv.FormatUint(uint64(sysUser.Id), 10), "1", int(l.svcCtx.Config.JwtAuth.AccessExpire))
	if err != nil {
		return nil, errorx.NewDefaultError(errorx.ServerErrorCode)
	}
	return &user.LoginResp{
		Token: token,
	}, nil
}

func (l *LoginLogic) getJwtToken(userId int64) (string, error) {
	iat := time.Now().Unix()
	claims := make(jwt.MapClaims)
	claims["exp"] = iat + l.svcCtx.Config.JwtAuth.AccessExpire
	claims["iat"] = iat
	claims[config.SysJwtUserId] = userId
	token := jwt.New(jwt.SigningMethodHS256)
	token.Claims = claims
	return token.SignedString([]byte(l.svcCtx.Config.JwtAuth.AccessSecret))
}
